from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView
from hlq import models
from . import serializer

class ArticleView(ListAPIView, CreateAPIView):
    queryset = models.Article.objects.all()
    # serializer_class = serializer.ArticleSerializers

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return serializer.PageArticleSerializers
        elif self.request.method == 'POST':
            return serializer.ArticleSerializers

    def perform_create(self, serializer):
        serializer.save()
# class ArticleView(APIView):
#     def get(self, request, *args, **kwargs):
#         id = request.query_params.get('id')
#         if not id:
#             condition = {}
#             category = request.query_params.get('category_id')
#             if category:
#                 condition['category'] = category
#                 print(condition)
#             queryset = models.Article.objects.filter(**condition).order_by('-date')
#             page = PageNumberPagination()
#             result = page.paginate_queryset(queryset, request, self)
#             ser = serializer.ArticleListSerializers(instance=result, many=True)
#             return Response(ser.data)
#
#         article_obj = models.Article.objects.filter(id=id).first()
#         ser = serializer.PageArticleSerializers(instance=article_obj, many=False)
#         return Response(ser.data)
#
#     def post(self, request, *args, **kwargs):
#         ser = serializer.ArticleSerializers(data=request.data)
#         ser_detail = serializer.ArticleDetailSerializers(data=request.data)
#         if ser.is_valid() and ser_detail.is_valid():
#             article_obj = ser.save(author_id=1)
#             ser_detail.save(article_id=article_obj.id)
#             return Response('保存成功')
#         return Response('保存失败')


class CommentView(APIView):
    def get(self, request, *args, **kwargs):
        article_id = request.query_params.get('article_id')
        queryset = models.Comment.objects.filter(article_id=article_id)
        ser = serializer.CommentSerializers(instance=queryset, many=True)
        return Response(ser.data)

    def post(self, request, *args, **kwargs):
        ser = serializer.PostCommentSerializers(data=request.data)
        if ser.is_valid():
            ser.save(user_id=1)
            return Response(ser.data)
        return Response(ser.errors)
